package com.znzz.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.znzz.domain.User;
import com.znzz.service.IUserService;
import com.znzz.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * 表现层
 */
@RestController//返回ajax
@RequestMapping("/users")
public class UserController {
    @Autowired
    private IUserService userService;

    @GetMapping//请求方式get请求
    public R getAll() {
//        if (true) throw new IOException();
        return new R(true, userService.list());
    }

    /* @RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的)*/
    @PostMapping
    public R save(@RequestBody User user) throws IOException {//请求体参数
       /* if (user.getName().equals("lisa")) {
            throw new IOException();
        }*/
//        "添加成功^_^" "添加失败-_-!"
        boolean flag = userService.save(user);
        return new R(flag, flag ? "添加成功^_^" : "添加失败-_-!");
    }

    @PutMapping
    public R update(@RequestBody User user) {
        return new R(userService.updateById(user));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable String id) {
        return new R(userService.removeById(id));
    }

    /*接收请求路径中占位符的值*/
    @GetMapping("{id}")
    public R getById(@PathVariable String id) {
        return new R(true, userService.getById(id));
    }

//    @GetMapping("{currentPage}/{pageSize}")
//    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize) {
//        /*如果当前页码值大于总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值*/
//        IPage<User> page = userService.getPage(currentPage, pageSize);
//        if (currentPage > page.getPages()) {
//            page = userService.getPage((int) page.getPages(), pageSize);
//        }
//        return new R(true, page);
//    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, User user) {
//        System.out.println(user);
        /*如果当前页码值大于总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值*/
        IPage<User> page = userService.getPage(currentPage, pageSize, user);
        if (currentPage > page.getPages()) {
            page = userService.getPage((int) page.getPages(), pageSize, user);
        }
        return new R(true, page);
    }
}
